/* jshint esversion: 6 */
import Vue from 'vue';
import Router from 'vue-router';
import NProgress from 'nprogress' // progress bar
const packageJson = require('../../package.json');

Vue.use(Router);


// 解决编程式路由往同一地址跳转时会报错的情况
const originalPush = Router.prototype.push,
    originalReplace = Router.prototype.replace;
// push
Router.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) {
        return originalPush.call(this, location, onResolve, onReject);
    }
    return originalPush.call(this, location).catch(err => err);
};
// replace
Router.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject) {
        return originalReplace.call(this, location, onResolve, onReject);
    }
    return originalReplace.call(this, location).catch(err => err);
};
// pages 下面所有的组件
const files = require.context('@/pages', true, /\.vue$/)
let pages = {};

files.keys().forEach(key => {
    pages[key.replace(/(\.\/|\.vue)/g, '')] = files(key).default;
})
// 大写字符串中每个单词的第一个字符
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase()),
    // 将字符串转换为camelCase
    toCamelCase = (str) => uppercaseWords(str.trim()).replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));

// 生成路由规则
let dynamicRoutes = [],
    flatMenu = [];
Object.keys(pages).forEach(item => {
    let pattBl = /(login|home|components)/g.test(item);
    if (pattBl) {
        return false
    }
    let path = '/' + item.toLowerCase(),
        name = toCamelCase(item.split('/')[item.split('/').length - 1].toLowerCase()),
        component = pages[item];
    // 大屏
    if (item.includes('data-visible')) {
        flatMenu.push({
            path,
            name,
            component
        })
        return false
    }
    dynamicRoutes.push({
        path,
        name,
        component
    })
});
console.log('二级路由', dynamicRoutes, '大屏路由', flatMenu);
// const Cate = () =>
//     import ( /* webpackChunkName: "cate_params" */ '@/pages/goods/Cate.vue')
// const Params = () =>
//     import ( /* webpackChunkName: "cate_params" */ '@/pages/goods/Params.vue')

// Vue嵌套路由
const router = new Router({
    mode: 'history',
    base: `/${packageJson.name}-${packageJson.version}`, // history模式下
    routes: [
    // 大屏路由
        ...flatMenu,
        // 一级路由
        { path: '/', redirect: '/login' },
        {
            name: 'login',
            path: '/login',
            component: () => import('@/pages/login.vue')
        },
        {
            name: 'home',
            path: '/home',
            component: () => import('@/pages/home.vue'),
            redirect: '/welcome',
            children: [
                // 二级路由
                ...dynamicRoutes
            ]
        },
        { path: '*', redirect: '/error-info' }
    ],
    // scrollBehavior 在使用keep-alive的时候会用到，处理滑动到上次的位置还是滑动到顶部
    scrollBehavior: (to, from, savedPosition) => {
        if (savedPosition) {
            return savedPosition;
        }
    }
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // start progress bar
    NProgress.start()
    console.log('to', to, 'from', from)
    // to将要访问的路径
    // from代表从哪个路径跳转而来
    // next是一个函数，表示放行
    // next()放行 next('/login')
    const tokenStr = window.sessionStorage.getItem('token')
    if (to.path !== '/login' && !tokenStr) {
        next('/login')
    } else {
        next()
    }
    NProgress.done()
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})
export default router